/*
 * Copyright (c) 2025 李伟国
 * SQL-API is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.moyu.sql.business.utils;

import com.sun.istack.NotNull;
import org.springframework.util.ObjectUtils;

import java.util.Map;

/**
 * 参数相关的工具类
 */
public class ParamUtils {

    /**
     * 判断是否是嵌套参数名
     */
    public static boolean isNestedParam(String paramName) {
        if (paramName == null) {
            return false;
        }
        return paramName.contains(".") && paramName.split("\\.").length > 1;
    }

    /**
     * 获取嵌套参数的值
     *
     * @param paramName  参数名
     * @param requestMap 请求参数Map
     * @return true/false
     */
    @SuppressWarnings("unchecked")
    public static Object getNestedParamValue(@NotNull String paramName, Map<String, Object> requestMap) {
        if (StringUtils.isBlank(paramName) || ObjectUtils.isEmpty(requestMap)) {
            // 参数名不存在直接返回false
            return null;
        }
        // 如果不是嵌套参数则直接返回参数值
        if (!isNestedParam(paramName)) {
            return requestMap.get(paramName);
        }
        // 获取第一个.之前的字符串
        String firstParamName = paramName.substring(0, paramName.indexOf("."));
        Object firstValueObject = requestMap.get(firstParamName);
        if (ObjectUtils.isEmpty(firstValueObject)) {
            return null;
        }
        // 获取第一个.之后的字符串
        String nextParamName = paramName.substring(paramName.indexOf(".") + 1);
        if (StringUtils.isBlank(nextParamName)) {
            return null;
        }

        if (firstValueObject instanceof Map) {
            Map<String, Object> nestedMap = (Map<String, Object>) firstValueObject;
            return getNestedParamValue(nextParamName, nestedMap);
        }
        return null;
    }

}
